{% extends "button.html" %}
{% block title %}
    <title>样本DNA使用记录信息</title>
{% endblock %}


{% block content %}
    <div class="jumbotron">
        <h1>甲基化早筛项目数据库管理系统Demo</h1>
        <h4>样本DNA使用记录</h4>
    </div>
{% endblock %}

{% block plot %}
    <div class="row">
        <div id="plot_highcharts" style="width: 550px; height: 400px; margin: 0 auto" class="col-9"></div>
        <div id="plot_button" class="form-group col-3">
            <label for="plot_highcharts_field"> 请选择用于画图的关键字段</label>
            <select class="form-control" id="plot_highcharts_field" name="plot_highcharts_field">
                <option value="usage" selected="selected">用途</option>
                <option value="LB_date">使用日期</option>
                <option value="mass">使用量</option>
            </select>
        </div>
    </div><br>
{% endblock %}

{% block table %}
    <!-- datatables -->
    <table id="table_id" class="display">
        <thead>
        <tr>
            <th>索引</th>
            <th>样本编号</th>
            <th>DNA提取编号</th>
            <th>使用日期</th>
            <th>使用量</th>
            <th>用途</th>
            <th>建库编号(如有)</th>
            <th>备注</th>
            <th>上次修改时间</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
    </table>
{% endblock %}

{% block ModalFormHeader %}
    <p id="ModalFormHeader" class="text-warning front-weight-bold"></p>
{% endblock %}

{% block ModalForm %}
    <div class="form-group">
        <span><a class="text-danger front-weight-bold">* </a>
            <label for="dna_id"> DNA提取编号</label></span>
        <input type="text" class="form-control" id="dna_id" name="dna_id"
               placeholder="请输入DNA提取编号，必填" required="true">
    </div>
    <div class="form-group">
        <label for="LB_date"> 使用日期</label>
        <input type="date" class="form-control" id="LB_date" name="LB_date"
               placeholder="请输入使用日期，默认：2000-01-01" required="true">
    </div>
    <div class="form-group">
        <label for="mass"> 使用量(ng)</label>
        <input type="number" step="0.01" class="form-control" id="mass" name="mass"
               placeholder="请输入使用量(ng)，默认：0" value="0">
    </div>
    <div class="form-group">
        <label for="usage"> 用途</label>
        <select class="form-control" id="usage" name="usage" required="true">
            <option value="建库失败" selected="selected">建库失败</option>
            <option value="科研项目">科研项目</option>
            <option value="其他">其他</option>
        </select>
    </div>
    <div class="form-group">
        <label for="others"> 备注</label>
        <input type="text" class="form-control" id="others" name="others"
               placeholder="请输入备注，默认：无" value="无">
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        $(document).ready(function () {
            let dataModelForm;
            let fieldForPie = $('#plot_highcharts_field');

            function MyModelInit(title_name, data) {
                dataModelForm = data;
                if (title_name === '更新') {
                    $('#dna_id').val(data['dna_id']);
                    $('#LB_date').val(data['LB_date']);
                    $('#mass').val(data['mass']);
                    $('#usage').val(data['usage']);
                    $('#others').val(data['others']);
                    $('#type').val('edit');
                    $('#modal_title').text('更新');
                } else {
                    $('#dna_id').val("");
                    $('#LB_date').val("2000-01-01");
                    $('#mass').val("");
                    $('#usage option:first').prop("selected", 'selected');
                    $('#others').val("");
                    $('#type').val('new');
                    $('#modal_title').text('新增');
                }
            }

            let table = $('#table_id').DataTable({
                "language": {
                    "lengthMenu": "选择每页 _MENU_ 展示 ",
                    "zeroRecords": "未找到匹配结果--抱歉",
                    "info": "当前显示第 _PAGE_ 页结果，共 _PAGES_ 页",
                    "infoEmpty": "没有数据",
                    "search": "搜索",
                    "infoFiltered": "(获取 _MAX_ 项结果)",
                    "paginate": {
                        "first": "首页",
                        "previous": "上一页",
                        "next": "下一页",
                        "last": "末页"
                    }
                },
                "scrollY": "5000px",
                "scrollCollapse": true,
                "pagingType": "full_numbers",
                rowReorder: true,
                colReorder: true,
                searching: true,
                select: true,
                dom: 'lB<"clear">frtip',
                buttons: [
                    {
                        extend: 'colvisGroup',
                        text: '显示前5列',
                        show: [0, 1, 2, 3, 4, 5, 10],
                        hide: [6, 7, 8, 9]
                    },
                    {
                        extend: 'colvisGroup',
                        text: '显示全部列',
                        show: ':hidden',
                    },
                    {
                        text: '指定显示列', extend: 'colvis',
                        postfixButtons: ['colvisRestore'],
                        columnText: function (dt, idx, title) {
                            return (idx + 1) + ': ' + title;
                        }
                    },
                    {
                        extend: 'selectAll',
                        text: '全选'
                    }, {
                        extend: 'selectRows',
                        text: '选择多行'
                    }, {
                        extend: 'selectNone',
                        text: '取消当前选择'
                    },
                    {
                        extend: 'copy',
                        text: '复制到剪切板',
                        exportOptions: {
                            columns: range(1, 9)
                        }
                    }, {
                        extend: 'csv',
                        text: '输出到csv',
                        exportOptions: {
                            columns: range(1, 9)
                        }
                    }
                ],
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
                "serverSide": true,
                "processing": true,
                "ajax": "/api/DNAUsageRecordInfo/?format=datatables",
                "deferRender": true,
                "columns": [
                    {
                        data: 'index',
                        width: "1%",
                        // 若想前端显示的不一样，则需要"render"函数
                        'render': function (data, type, full, meta) {
                            return meta.row + 1 + meta.settings._iDisplayStart;
                        }
                    },
                    {"data": "sample_id", "name": "sample_id__sample_id"},
                    {"data": "dna_id", "name": "dna_id__dna_id"},
                    {"data": "LB_date"},
                    {"data": "mass"},
                    {"data": "usage"},
                    {"data": "singleLB_id"},
                    {"data": "others"},
                    {"data": "last_modify_date"},
                    {"data": "created"},
                    {
                        "data": null,
                        render: function (data, type, row, meta) {
                            if (row.usage === '建库成功') {
                                return ""
                            }
                        },
                        "defaultContent": '<button type="button" class="btn btn-info">更新</button>' + '&nbsp;&nbsp' +
                            '<button type="button" class="btn btn-danger">删除</button>'
                    }
                ]
            });
            table.button(0).trigger();

            let url = '/api/DNAUsageRecordInfo/';
            let url2 = '/api/DNAInventoryInfo/';
            let data;
            $('#table_id tbody').on('click', 'button', function () {
                data = table.row($(this).parents('tr')).data();
                let class_name = $(this).attr('class');
                if (data['usage'] !== '建库成功') {
                    if (class_name === 'btn btn-info') {
                        // EDIT button
                        MyModelInit('更新', data);
                        $('#ModalFormHeader').text("");
                        $("#myModal").modal();
                    } else {
                        // DELETE button
                        //alert('delete '+id);
                        //$('#modal_title').text('DELETE');
                        $("#confirm").modal();
                    }
                } else {
                    $(this).css("background-color", "grey");
                }
            });

            $('#modelForm').on('submit', function (e) {
                e.preventDefault();

                // 递交前检查，一般是检测model的外键是否存在
                let data0 = $.ajax({
                    url: url2, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: {dna_id: $('#dna_id').val()}
                }).responseJSON[0];
                if (data0 === undefined) {
                    $('#myModalError').text('错误！！！DNA提取编号不存在，请填写正确的DNA提取编号。');
                    return
                }

                let type = $('#type').val();
                let method = '';
                let url_ajax = url;
                if (type === 'new') {
                    // new
                    method = 'POST';
                } else {
                    // edit
                    url_ajax = url + data['index'] + '/';
                    method = 'PUT';
                }

                // 记录库存表条目变化
                let data_tmp2;
                if (method === 'POST') {
                    if ($('#usage').val() === '建库失败') {
                        data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM,
                            failM: data0.failM + $('#mass').val(), researchM: data0.researchM,
                            othersM: data0.othersM
                        });
                    } else if ($('#usage').val() === '科研项目') {
                        data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM,
                            failM: data0.failM, researchM: data0.researchM + $('#mass').val(),
                            othersM: data0.othersM
                        });
                    } else if ($('#usage').val() === '其他') {
                        data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM,
                            failM: data0.failM, researchM: data0.researchM,
                            othersM: data0.othersM + $('#mass').val()
                        });
                    }
                } else {
                    sub = $('#mass').val() - data0['mass'];
                    if ($('#usage').val() === '建库失败') {
                        data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM,
                            failM: data0.failM + sub, researchM: data0.researchM,
                            othersM: data0.othersM
                        });
                    } else if ($('#usage').val() === '科研项目') {
                        data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM,
                            failM: data0.failM, researchM: data0.researchM + sub,
                            othersM: data0.othersM
                        });
                    } else if ($('#usage').val() === '其他') {
                        data_tmp2 = $.param({
                            dna_id: data0.dna_id, sample_id: data0.sample_id,
                            totalM: data0.totalM, successM: data0.successM,
                            failM: data0.failM, researchM: data0.researchM,
                            othersM: data0.othersM + sub
                        });
                    }
                }

                // 增、改：更新使用记录表
                $.ajax({
                    url: url_ajax, async: false,
                    method: method,
                    data: $(this).serialize() + '&' + $.param({
                        sample_id: data0.sample_id, singleLB_id: '无'
                    }),
                    headers: {'X-HTTP-Method-Override': 'PATCH'},
                    success: function () {
                        let v_tmp = $('#dna_id').val();
                        // 改：更新库存表
                        $.ajax({
                            url: url2 + data0.index + '/',
                            method: 'PUT',
                            data: data_tmp2,
                            headers: {'X-HTTP-Method-Override': 'PATCH'},
                            success: function () {
                                databaseRecordAjaxPut("DNAInventoryInfo", "单项更新", "DNA提取编号：" + v_tmp);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                            }
                        });

                        if (type === 'new') {
                            databaseRecordAjaxPut("DNAUsageRecordInfo", "单项添加", "DNA提取编号：" + v_tmp);
                            $('#myModalError').text('添加成功！！！DNA提取编号：' + v_tmp);
                        } else {
                            databaseRecordAjaxPut("DNAUsageRecordInfo", "单项更新", "DNA提取编号：" + v_tmp);
                            $('#myModalError').text('更新成功！！！DNA提取编号：' + v_tmp);
                        }

                        setTimeout(
                            function () {
                                window.location.reload(true);
                            }, 3000
                        );
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $('#myModalError').text('出现错误！！！请联系管理员');
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });
            });

            $('#confirm').on('click', '#delete', function (e) {
                let data0 = $.ajax({
                    url: url2, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: {dna_id: data['dna_id']}
                }).responseJSON[0];
                let data_tmp2;
                if (data['usage'] === '建库失败') {
                    data_tmp2 = $.param({
                        dna_id: data0.dna_id, sample_id: data0.sample_id,
                        totalM: data0.totalM, successM: data0.successM,
                        failM: data0.failM - data['mass'], researchM: data0.researchM,
                        othersM: data0.othersM
                    });
                } else if (data['usage'] === '科研项目') {
                    data_tmp2 = $.param({
                        dna_id: data0.dna_id, sample_id: data0.sample_id,
                        totalM: data0.totalM, successM: data0.successM,
                        failM: data0.failM, researchM: data0.researchM - data['mass'],
                        othersM: data0.othersM
                    });
                } else if (data['usage'] === '其他') {
                    data_tmp2 = $.param({
                        dna_id: data0.dna_id, sample_id: data0.sample_id,
                        totalM: data0.totalM, successM: data0.successM,
                        failM: data0.failM, researchM: data0.researchM,
                        othersM: data0.othersM - data['mass']
                    });
                }

                // 删： 更新使用记录表
                $.ajax({
                    url: url + data['index'] + '/',
                    method: 'DELETE',
                    success: function () {
                        // 删：更新库存表
                        $.ajax({
                            url: url2 + data0.index + '/',
                            method: 'PUT',
                            data: data_tmp2,
                            headers: {'X-HTTP-Method-Override': 'PATCH'},
                            success: function () {
                                databaseRecordAjaxPut("DNAInventoryInfo", "单项更新", "使用记录表发生单项删除操作，" +
                                    "改变index：" + data0.index);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                            }
                        });
                        databaseRecordAjaxPut("DNAUsageRecordInfo", "单项删除", "index：" + data['index']);
                        window.location.reload(true);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                    }
                });
            });


            $('#new').on('click', function (e) {
                MyModelInit('新增', {});
                $('#ModalFormHeader').text('只能添加 非“建库成功” 的记录，如需添加 “建库成功” 记录，请到样本建库信息页面');
                $("#myModal").modal();
            });

            $('#upload').on('click', function (e) {
                $('#uploadOperator').val("");
                $('#uploadFile').val("");
                $('#uploadError').val("");
                $('#uploadUrl').val('DNAUsageRecordInfo');
                $("#uploadModal").modal();
            });

            $('#bulkDel').on('click', function (e) {
                $('#bulkDelUrl').val('DNAUsageRecordInfo');
                $("#bulkDelModal").modal();
            });

            $('.downloadExcel').on('click', function (e) {
                e.preventDefault();
                window.location.href = '/download_excel/DNAUsageRecordInfo/'
            });

            $('#myModalReset').on('click', function (e) {
                e.preventDefault();
                if ($('#modal_title').text() === '更新') {
                    MyModelInit('更新', dataModelForm);
                } else {
                    MyModelInit('新增', {});
                }
            });

            pie_plot('DNAUsageRecordInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());

            fieldForPie.change(function () {
                pie_plot('DNAUsageRecordInfo', fieldForPie.val(), fieldForPie.find("option:selected").text());
            });

            $("#modelForm input[type='text']").focus(function () {
                let key2 = $(this).attr('id');
                let values = $.ajax({
                    url: "{% url 'unique' %}", data: {model: "DNAUsageRecordInfo", filed: key2},
                    dataType: 'json', contentType: "application/json",
                    method: "GET", async: false
                }).responseJSON.values;
                console.info("values:", values, "; key2:", key2);
                input_autocomplete(values, '#' + key2);
            });
        })

    </script>
{% endblock %}